<script setup lang="ts">
import { ref, computed, nextTick } from 'vue';
const props = defineProps({
  tabs: {
    type: Array,
    default: () => [],
  },
});
const tabs = computed(() => props.tabs);
// 当前选中的 tab 索引
const currentIndex = ref(0);

// 控制 scroll-view 的滚动位置
const scrollLeft = ref(0);

// 每个 tab 的宽度（假设每个 tab 宽度相同）
const tabWidth = 72; // 100px 图片宽度 + 10px 右边距

// 计算 scroll-view 的滚动位置
const calculateScrollLeft = (index) => {
  const screenWidth = uni.getSystemInfoSync().windowWidth; // 获取屏幕宽度
  console.log(screenWidth);
  const halfScreenWidth = screenWidth / 2; // 屏幕宽度的一半
  const targetScrollLeft = index * tabWidth - halfScreenWidth + tabWidth / 2; // 目标滚动位置

  // 边界处理：不能滚动到负数或超过最大滚动范围
  const maxScrollLeft = tabs.value.length * tabWidth - screenWidth;
  return Math.max(0, Math.min(targetScrollLeft, maxScrollLeft));
};

// 切换 tab
const changeTab = (index) => {
  currentIndex.value = index;
  scrollLeft.value = calculateScrollLeft(index);
};
</script>

<template>
  <view class="tabs-container">
    <!-- scroll-view 实现横向滚动 -->
    <scroll-view
      class="tabs-scroll"
      scroll-x="true"
      scroll-with-animation
      :scroll-left="scrollLeft"
      scroll-animation-duration="300"
    >
      <view class="tabs">
        <!-- 遍历 tabs，渲染每个 tab -->
        <view
          v-for="(tab, index) in tabs"
          :key="index"
          class="tab-item"
          :class="{ active: currentIndex === index }"
          @click="changeTab(index)"
        >
          <image :src="tab.image" mode="aspectFill" class="tab-image"></image>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<style scoped>
.tabs-container {
  width: 100%;
  white-space: nowrap;
}

.tabs-scroll {
  width: 100%;
  overflow-x: auto;
}

.tabs {
  display: flex;
}

.tab-item {
  flex: 0 0 auto;
  margin-right: 10px;
  position: relative;
}

.tab-image {
  width: 60px;
  height: 60px;
  border-radius: 5px;
  border: 1px solid pink;
}

.active .tab-image {
  border: 1px solid #007aff;
}
</style>
